package net.b521.petshop.service.impl;


import net.b521.petshop.dao.OrderItemMapper;
import net.b521.petshop.dao.OrderMapper;
import net.b521.petshop.dao.ProductMapper;
import net.b521.petshop.dao.model.*;
import net.b521.petshop.service.OrderService;
import net.b521.petshop.service.ShopCartService;
import net.b521.petshop.service.exception.LoginException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;


    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ShopCartService shopCartService;


    @Override
    public Order findById(int id) {
        return orderMapper.selectByPrimaryKey(id);
    }


    @Override
    public List<Order> findAll() {
        return orderMapper.selectByExample(null);
    }

    @Override
    public List<Order> findBySeller(Seller seller) {
        OrderExample orderExample = new OrderExample();
        orderExample.createCriteria().andSellerIdEqualTo(seller.getId());
        return orderMapper.selectByExample(orderExample);
    }



    @Override
    public void update(Order order) {
        orderMapper.updateByPrimaryKeySelective(order);
    }

    @Override
    public int create(Order order) {
        return orderMapper.insertSelective(order);
    }

    @Override
    public void delById(int id) {
        orderMapper.deleteByPrimaryKey(id);
    }

    /**
     * 查询订单项详情
     * @param orderId
     * @return
     */
    @Override
    public List<OrderItem> findItems(int orderId) {

        OrderItemExample orderItemExample = new OrderItemExample();
        orderItemExample.createCriteria().andOrderIdEqualTo(orderId);
        List<OrderItem> orderItems = orderItemMapper.selectByExample(orderItemExample);

        // OrderItem item = orderItemMapper.selectByPrimaryKey(orderId);
        // List<OrderItem> list = Lists.newArrayList();
        // list.add(item);


        // List<OrderItem> list = orderItemDao.findByOrderId(orderId);
        for (OrderItem orderItem : orderItems) {
            // Product product = productDao.findOne(orderItem.getProductId());
            Product product = productMapper.selectByPrimaryKey(orderItem.getProductId());
            orderItem.setProduct(product);
        }
        // return list;
        return orderItems;
    }

    /**
     * 更改订单状态
     *
     * @param id
     * @param status
     */
    @Override
    public void updateStatus(int id, int status) {
        // Order order = orderDao.findOne(id);
        Order order = orderMapper.selectByPrimaryKey(id);
        order.setState(status);
        // orderDao.save(order);
        orderMapper.updateByPrimaryKeySelective(order);
    }

    /**
     * 查找用户的订单列表
     *
     * @param request
     * @return
     */
    @Override
    public List<Order> findUserOrder(HttpServletRequest request) {
        //从session中获取登录用户的id，查找他的订单
        Object user = request.getSession().getAttribute("user");
        if (user == null){
            throw new LoginException("请登录！");
        }
        User loginUser = (User) user;

        OrderExample orderExample = new OrderExample();
        orderExample.createCriteria().andUserIdEqualTo(loginUser.getId());
        List<Order> orders = orderMapper.selectByExample(orderExample);
        // List<Order> orders = orderDao.findByUserId(loginUser.getId());
        return orders;
    }

    /**
     * 支付
     *
     * @param orderId
     */
    @Override
    public void pay(int orderId) {
        //具体逻辑就不实现了，直接更改状态为 待发货
        // Order order = orderDao.findOne(orderId);
        Order order = orderMapper.selectByPrimaryKey(orderId);
        if (order == null){
            throw new RuntimeException("订单不存在");
        }
        // orderDao.updateState(STATE_WAITE_SEND,order.getId());
        // update `p_order` o set o.state=?1 where o.id=?
        int i = orderMapper.updateState(OrderService.STATE_WAITE_SEND, order.getId());
        System.out.println(i);


    }

    /**
     * 提交订单
     *
     * @param name
     * @param phone
     * @param addr
     * @param request
     * @param response
     */
    @Override
    @Transactional
    public void submit(String name, String phone, String addr, Integer seller, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Object user = request.getSession().getAttribute("user");
        if (user == null){
            throw new LoginException("请登录！");
        }
        User loginUser = (User) user;
        List<Integer> productIds = (List) request.getSession().getAttribute("shop_cart_" + ((User) user).getId());

        ProductExample productExample = new ProductExample();
        productExample.createCriteria().andIdIn(productIds);
        List<Product> products = productMapper.selectByExample(productExample);

        if (products != null) {

            Order order = new Order();
            order.setName(name);
            order.setPhone(phone);
            order.setAddr(addr);
            order.setSellerId(products.get(0).getSellerId());
            order.setOrderTime(new Date());
            order.setUserId(loginUser.getId());
            order.setState(STATE_NO_PAY);
            Double total = 0.0;
            order.setTotal(total);

            orderMapper.insertSelective(order);
            // order = orderDao.save(order);

            List<OrderItem> orderItems = shopCartService.listCart(request);
            for (OrderItem orderItem : orderItems) {
                // orderItem.setSellerId(seller);
                orderItem.setOrderId(order.getId());
                total += orderItem.getSubTotal();

                orderItemMapper.insertSelective(orderItem);
                // orderItemDao.save(orderItem);
            }
            order.setTotal(total);

            orderMapper.updateByPrimaryKeySelective(order);

        }




        // orderDao.save(order);
        //重定向到订单列表页面
        response.sendRedirect("/mall/order/toList.html");
    }

    /**
     * 确认收货
     *
     * @param orderId
     */
    @Override
    public void receive(int orderId) {
        // Order order = orderDao.findOne(orderId);
        Order order = orderMapper.selectByPrimaryKey(orderId);
        if (order == null){
            throw new RuntimeException("订单不存在");
        }
        order.setState(STATE_COMPLETE);
        // orderDao.updateState(STATE_COMPLETE,order.getId());
        orderMapper.updateByPrimaryKeySelective(order);
    }
}
